<template>
  <el-dialog class="assign-role" title="标题" :visible="showRoleDialog" @close="closeDialog" @open="openDialog">
    <el-checkbox-group v-model="roleIds" v-loading="loading">
      <el-checkbox v-for="item in list" :key="item.id" :label="item.id">{{ item.name }}</el-checkbox>
    </el-checkbox-group>
    <template #footer>
      <el-button type="primary" size="small" @click="clickSubmit">确定</el-button>
      <el-button size="small" @click="closeDialog">取消</el-button>
    </template>
  </el-dialog>

</template>

<script>
import { reqGetRoleList } from '@/api/setting'
import { reqGetUserinfoByid } from '@/api/user'
import { reqAssignRoles } from '@/api/employees'
export default {
  name: 'AssignRole',
  props: {
    showRoleDialog: {
      type: Boolean,
      default: false
    },
    userId: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      list: [],
      roleIds: [],
      loading: false
    }
  },
  created() {
    // this.getRoleList()
    // this.getUserinfoByid()
  },
  methods: {
    // 关闭弹窗
    closeDialog() {
      this.$emit('update:showRoleDialog', false)
    },
    // 打开弹窗发送请求
    // created 中直接发请求会有问题, 一进入页面, 弹框还没点就发请求了, 而此时还没有 userId
    openDialog() {
    //   this.getRoleList()
    //   this.getUserinfoByid()
      this.loading = true
      Promise.all([this.getRoleList(), this.getUserinfoByid()]).then(() => {
        this.loading = false
      })
    },
    async getRoleList() {
      const { data } = await reqGetRoleList(1, 100)
      this.list = data.rows
      //   console.log(data)
      return data.list
    },
    // 获取用户当前角色
    async getUserinfoByid() {
      const { data } = await reqGetUserinfoByid(this.userId)
      this.roleIds = data.roleIds
      return data.roleIds
    },
    // 更新用户角色
    async clickSubmit() {
      await reqAssignRoles({
        id: this.userId,
        roleIds: this.roleIds
      })
      this.$message.success('更新角色成功')
      this.closeDialog()
    }
  }
}
</script>

<style lang="scss" scoped>
.assign-role {
  ::v-deep {
    .el-checkbox {
      font-size: 30px;
    }
  }
}
</style>
